// pages/homepage/homepage.js

const db = wx.cloud.database()
const cont = db.collection('bgMallImg');

var util = require('../../utils/utils.js');
const innerAudioContext = wx.createInnerAudioContext();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    time:"",
    data:'',
    hours:"",
    TimeText:'',
    ImgUrl:'',
    changeText:[
      '睡眠',
      '专注',
      '呼吸'
    ],
    isplay:false,
    
    index:0,
    navState:0,
    // 主题背景图片
    imgUrls:[
      'cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Images/雷雨首页底图.jpg',
      'cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Images/森林首页底图.jpg',
      'cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Images/海浪首页底图.jpg'
    ],
    // 音源
    changeStyleMusic:[
      'cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Sleep_music/海浪之旅.mp3',
      'cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Sleep_music/曼妙钢琴.mp3'
    ],
    // 海报数据
    cardPath: 'cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Images/海报.png',
    headPath: 'cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Images/张伟.jpg',
    sendName: '阿巴阿巴阿巴阿巴',
    //云开发数据库存储数组
    bgMallImg:[],
    //定时器picker数据
    multiArray:[["0","1","2","3","4","5","6","7","8","9","10","11","12"],["小时"],["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"],["分钟"]]
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
    innerAudioContext.play();    
    console.log(innerAudioContext.duration);    
    this.setData({ isplay: true });//定时后播放
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var TIME = util.formatTime(new Date());
    this.setData({
      time:TIME
    })


    
    var Hours = util.formatHour(new Date())
    this.setData({
      hours:Hours
    })
    console.log(Hours[0])
    if(Hours <= 12){
      this.setData({
        TimeText:'早上好'
      })
    }else if(Hours <= 18){
      this.setData({
        TimeText:'下午好'
      })
    }else if(Hours <= 21){
      this.setData({
        TimeText:'晚上好'
      })
    }else {
      this.setData({
        TimeText:'夜深了'
      })
    }

    // 调用系统信息获取窗框宽高（形成等大画布）
    var that = this;
    wx: wx.getSystemInfo({
      success: function (res) {
        that.setData({
          pixelRatio: res.pixelRatio,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        })
      }
    })
    that.drawCanvas();

    // 云开发调用函数
    db.collection('bgMallImg').get({

      success: (res) => {
        console.log(res.data);

        this.setData({
          bgMallImg:res.data
        })

      }
    })
    
  },
  //显示底部弹出框
  clickme:function(){
    this.showModal();
  },
  //显示对话框
 showModal: function () {
  // 显示遮罩层
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "linear",
    delay: 0
  })
  this.animation = animation
  animation.translateY(300).step()
  this.setData({
    animationData: animation.export(),
    showModalStatus: true
  })
  setTimeout(function () {
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export()
    })
  }.bind(this), 200)
},
//隐藏对话框
hideModal: function () {
  // 隐藏遮罩层
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "linear",
    delay: 0
  })
  this.animation = animation
  animation.translateY(300).step()
  this.setData({
    animationData: animation.export(),
  })
  setTimeout(function () {
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: false
    })
  }.bind(this), 200)
},
  //Canvas画图
  drawCanvas: function () {
    this.setData({
      cardPath: this.data.cardPath,
      headPath: this.data.headPath,
      sendName: this.data.sendName
    });
    let ctx = wx.createCanvasContext('myCanvas');
    let ctxW = this.data.windowWidth;
    let ctxH = 1210;
    // 默认像素比
    let pixelRatio = this.data.pixelRatio;
 
    // 垂直渐变
    const grd = ctx.createLinearGradient(0, 0, 0, ctxH);
    grd.addColorStop(0, '#ffffff');
    grd.addColorStop(1, '#ffffff');
    ctx.setFillStyle(grd);
    ctx.fillRect(0, 0, ctxW, ctxH);
 
    wx.getImageInfo({
      src: this.data.cardPath,
      success: (res) => {
        ctx.drawImage(res.path, 15, 15, 345, 470); //card
        wx.getImageInfo({
          src: this.data.headPath,
          success: (res) => {
            /**/
            ctx.arc(46,358,25, 0, 2 * Math.PI)
            ctx.fill()
            ctx.save();
            ctx.beginPath(); //开始绘制
            ctx.clip(); //剪切
            ctx.drawImage(res.path, 23, 333, 50, 50); //userHeader
            ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
            /**/
 
            ctx.setTextAlign('left');
            ctx.setTextBaseline('middle');
            ctx.setFontSize(16);
            ctx.setFillStyle('#fff');
            // 字体调整位置样式
            this.fontLineFeed(ctx, this.data.sendName, 450, 30, 79, 328);
            ctx.stroke();
            ctx.draw();
          }
        })
 
      }
    })
  },
  // 文字换行（字少没有也用不太到，先放着了）
  fontLineFeed: function (ctx, str, splitLen, strHeight, x, y) {
    let strArr = [];
    for (let i = 0, len = str.length / splitLen; i < len; i++) {
      strArr.push(str.substring(i * splitLen, i * splitLen + splitLen));
    }
    let s = 0;
    for (let j = 0, len = strArr.length; j < len; j++) {
      s = s + strHeight;
      ctx.fillText(strArr[j], x, y + s);
    }
  },

  //  分享下弹框
  buttonclick:function(){
    wx.showActionSheet({
      itemList: ["生成海报"],
      success(res){
          wx.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: function (res) {
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(result) {
                  wx.showToast({
                    title: '图片保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
              })
            }
          })
      }
    })

  },






  changeStyle:function(){
    data-index == index;
    if(index==0){
      this.setData({
        ImgUrl : '../../images/Mine.png'
      })
    }
  },

  bindchange(e) {
    let index = e.detail.current;
    this.setData({
      navState:index
    })
  },
  navSwitch: function(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      navState:index
    })
  },
    



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // setTimeout(() => {
    //   var i = 0
    //   var muSrc=this.data.bgMallImg  //[0].musicSrc
    //   innerAudioContext.src = "{{muSrc}}"
    //   console.log(muSrc.index)
    //   console.log("三秒钟到了")
    // },3000)
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var innerAudioSrc = innerAudioContext.src
    innerAudioSrc = "{{this.data.navState}}"
    if(this.data.navState==0){
      innerAudioContext.src = "cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Sleep_music/海浪之旅.mp3"
    }else if(this.data.navState==1){
      innerAudioContext.src = "cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Sleep_music/曼妙钢琴.mp3"
    }else{
      innerAudioContext.src = "cloud://yun-test-xah29.7975-yun-test-xah29-1302203904/Sleep_music/雷雨屋檐.mp3"
    }
  
  },

  //播放  
  play: function () {     
    innerAudioContext.play();    
    console.log(innerAudioContext.duration);    
    this.setData({ isplay: true });  },  // 停止  
  stop: function () {    
    innerAudioContext.pause();    
    this.setData({ isplay: false });  },
  
  // 商城试听播放
  mallPlay: function () {     
    innerAudioContext.play();    
    console.log(innerAudioContext.duration);    
    this.setData({ isplay: true });  },  // 停止  
  mallStop: function () {    
    innerAudioContext.pause();    
    this.setData({ isplay: false });  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindchange(e) {
    let index = e.detail.current;
    this.setData({
      navState:index
    })
  },
  navSwitch: function(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      navState:index
    })
  },
})